import { Component, OnInit } from '@angular/core';
import { HttpService } from '@core/services/http.service';
import { ActivatedRoute, Router } from '@angular/router';
import swal from 'sweetalert2';

@Component({
    selector: 'app-add-project',
    templateUrl: './add-project.component.html',
    styleUrls: ['./add-project.component.less']
})
export class AddProjectComponent implements OnInit {

    id;
    typeName = '';
    IP_PORT = this.http.IP_PORT;
    modify = false;
    user_id = JSON.parse(localStorage.getItem('_user')).user_id;
    maj_id;
    majorList = [];
    glMajList = [];
    glMajArr = [];

    classList = []
    glClaList = [];
    glClaArr = [];
    isCloud = '';
    role = JSON.parse(localStorage.getItem('_user')).role;



    data = {
        deviceType: 'pc',
        p_name: '',
        p_image: '',
        p_width: 0,
        p_height: 0,
        p_description: '',
        p_type: <any>'',
        process_type: <any>'',
        majarr: this.glMajArr,
        claarr: this.glClaArr,
        isCloud: this.isCloud
    };





    process_disabled = false;

    process_type = [
        { value: 'proces', label: '流程' },
        { value: 'debate', label: '辩论' },
        { value: 'role', label: '角色' }
    ]
    type = [
        {
            value: 'warning', label: '危机演练'
        },
        {
            value: 'public', label: '公共管理'
        },
        {
            value: 'gold', label: '沙漠掘金'
        }
    ]

    constructor(public http: HttpService, public router: Router, private ActiveRoute: ActivatedRoute) { }

    ngOnInit() {

        this.ActiveRoute.params.subscribe(res => {
            this.typeName = res.type;
            this.isCloud = res.type;
            this.data.isCloud = res.type;
            // console.log(res.type);
            if (res.id !== '0') {
                this.id = res.id;

                if (this.id === 0) {
                    this.process_disabled = false;
                } else {
                    this.process_disabled = true;
                }

                this.modify = true;
                this.http.getProjectById({ p_id: this.id, isCloud: this.typeName }).subscribe(data => {
                    console.log(data);
                    let claArr = data['claArr'];
                    let majArr = data['majArr'];

                    this.data = data['list'][0];
                    const type = JSON.parse(data['list'][0]['p_type']);
                    const process_type = JSON.parse(data['list'][0]['process_type']);


                    if (process_type.value === 'proces') {
                        this.data.process_type = this.process_type[0];
                    } else if (process_type.value === 'debate') {
                        this.data.process_type = this.process_type[1];
                    } else {
                        this.data.process_type = this.process_type[2];
                    }


                    if (type.value === 'public') {
                        this.data.p_type = this.type[1];
                    } else if (type.value === 'gold') {
                        this.data.p_type = this.type[2];
                    } else {
                        this.data.p_type = this.type[0];
                    }
                    this.data.deviceType = 'pc';
                    if (claArr.length) {
                        for (let cla of claArr) {
                            this.glClaArr.push(cla.cla_id);
                            this.glClaList.push(cla.cla_name);
                        }
                    }
                    if (majArr.length) {
                        this.maj_id = majArr[0].maj_Id;
                        for (let maj of majArr) {
                            this.glMajList.push(maj.major_name);
                            this.glMajArr.push(maj.maj_Id);
                        }
                    }

                    if (this.role != 3) {
                        this.getMajorList();
                        this.getClassByMajId(0)
                    }
                });
            } else {
                this.data.p_type = this.type[0];
                this.data.process_type = this.process_type[2];
                this.getMajorList();
            }
        });
        //console.log(this.process_disabled)

    }

    getMajorList() {
        this.http.getMajTech({ tech_id: this.user_id }).subscribe(res => {
            //console.log(res)
            this.majorList = res['list'];
            for (let list of this.majorList) {
                //console.log(list)
                list['ischeck'] = false;
                if (this.process_disabled) {
                    for (let mid of this.glMajArr) {
                        if (list.maj_id == mid) {
                            list.ischeck = true;
                        }
                    }
                }
            }
        })
    }

    getClassByMajId(i) {
        this.maj_id = this.glMajArr[i];
        if (this.maj_id) {
            this.http.getClassByMajId({ maj_id: this.maj_id }).subscribe(res => {
                //console.log(res);
                this.classList = res['list'];
                for (let list of this.classList) {
                    list['ischeck'] = false;
                    for (let cla of this.glClaArr) {
                        if (list.cla_id == cla) {
                            list.ischeck = true;
                        }
                    }
                }
            })
        }

    }

    majChange($event, major) {
        if ($event.target.checked) {
            this.glMajArr.push(major.maj_id);
            this.glMajList.push(major.major_name);
        } else {
            this.removeByValue(this.glMajArr, major.maj_id);
            this.removeByValue(this.glMajList, major.major_name);
            if (!this.glMajArr.length) {
                this.glClaArr = [];
                this.glClaList = [];
                this.classList = [];
            }
        }
    }

    clChange($event, cla) {
        if ($event.target.checked) {
            this.glClaArr.push(cla.cla_id);
            this.glClaList.push(cla.cla_name);
        } else {
            this.removeByValue(this.glClaArr, cla.cla_id);
            this.removeByValue(this.glClaList, cla.cla_name);
        }
    }

    removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }

    fileChange($event) {
        const file: File = $event.target.files[0];
        const myReader: FileReader = new FileReader();
        const that = this;
        myReader.onloadend = (loadEvent: any) => {
            this.IP_PORT = null;
            this.data.p_image = loadEvent.target.result;
        };
        myReader.readAsDataURL(file);
    }

    posting = false;
    save() {
        if (this.posting) {
            swal(`请不要重复提交!`, '', 'warning');
            return false;
        }
        if (!this.modify) {
            this.addProject();
        } else {
            this.updataProject();
        }
    }

    next() {
        if (this.posting) {
            swal(`请不要重复提交!`, '', 'warning');
            return false;
        }
        if (!this.modify) {
            this.addProject(true);
        } else {
            this.updataProject(true);
        }
    }

    updataProject(next?: boolean) {
        this.data['claarr'] = this.glClaArr;
        this.data['majarr'] = this.glMajArr;
        for (const key in this.data) {
            if (this.data[key] === '') {
                swal(`必填选项不能为空!`, '', 'warning');
                return false;
            }
        }
        if (this.role != 3) {
            if (!this.data.majarr.length) {
                swal(`专业为必填选项不能为空!`, '', 'warning');
                return false;
            }
            if (!this.data.claarr.length) {
                swal(`班级为必填选项不能为空!`, '', 'warning');
                return false;
            }
            this.data['isCloud'] = this.typeName;
        } else {
            this.data['isCloud'] = this.typeName;
        }

        this.posting = true;

        this.http.updateProjectById(this.data).subscribe(res => {
            if (res.code === '0') {
                // 控制跳转至流程,需要携带返回的id,宽度等信息;
                if (next) {
                    this.router.navigate(['../../../flows'],
                        {
                            relativeTo: this.ActiveRoute, queryParams: { p_id: this.id, p_width: this.data.p_width, p_height: this.data.p_height, process_type: this.data.process_type.value, type_name: this.data.isCloud }

                            // relativeTo: this.ActiveRoute, queryParams: { data: this.data }           // skipLocationChange: true
                        }
                    );
                } else {
                    swal(`${res['msg']}`, '', 'info');
                    if (this.role == 3) {
                        this.router.navigate(['/management']);
                    } else {
                        this.router.navigate(['xiangmu/full/pro-list/private']);
                    }

                }
            } else {
                swal(`${res['msg']}`, '', 'info');
            }

            this.posting = false;
        });
    }

    addProject(next?: boolean) {
        console.log(this.data)
        for (const key in this.data) {
            if (this.data[key] === '') {
                swal(`必填选项不能为空!`, '', 'warning');
                return false;
            }
        }
        if (this.role != 3) {
            if (!this.data.majarr.length) {
                swal(`专业为必填选项不能为空!`, '', 'warning');
                return false;
            }
            if (!this.data.claarr.length) {
                swal(`班级为必填选项不能为空!`, '', 'warning');
                return false;
            }
            this.data['isCloud'] = this.typeName;
        } else {
            this.data['isCloud'] = this.typeName;
        }

        this.posting = true;
        this.http.addProject(this.data).subscribe(res => {
            if (res.code === '0') {
                const id = res.p_id;

                swal(`${res['msg']}`, '', 'info');

                // 控制跳转至流程,需要携带返回的id,宽度等信息;
                if (next) {
                    console.log(this.data.isCloud);
                    this.router.navigate(['../../../flows'],
                        {
                            relativeTo: this.ActiveRoute, queryParams: { p_id: id, p_width: this.data.p_width, p_height: this.data.p_height, process_type: this.data.process_type.value, type_name: this.data.isCloud }
                            // skipLocationChange: true
                        }
                    );
                } else {
                    if (this.role == 3) {
                        this.router.navigate(['/management']);
                    } else {
                        this.router.navigate(['xiangmu/full/pro-list/private'],);
                    }
                }
                this.posting = false;
            }
        });
    }

    cancel() {
        if (this.role == 3) {
            this.router.navigate(['/management']);
        } else {
            this.router.navigate(['xiangmu/full/pro-list/private']);
        }

    }

    setLocalStorage(data) {
        console.log(data);
    }

}
